package client;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import ocsf.client.ObservableClient;

/**
 * The Class SGIClient.
 * handles message from observable OCSF server and delivers them to observers.
 * @author Tomer Elkayam
 */
public class SGIClient extends ObservableClient
{
	
	/** The photo flag. if a photo is sent - set to true */
	private static boolean photoFlag;
	
	/**
	 * Instantiates a new SGI client.
	 *
	 * @param host the host
	 * @param port the port
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	public SGIClient(String host, int port) throws IOException 
	{
		super(host, port);
		openConnection();
		photoFlag = false;
	}

	 /**
	   * This method is used to handle messages from the server.  This method
	   * can be overriden but should always call notifyObservers().
	   *
	   * @param message The message received from the client.
	   */
	@Override
	  protected void handleMessageFromServer(Object message)
	  {
		CliMessage climsg;
		setChanged();
		
		//cast the message to serialized result set
		ArrayList<HashMap<String,String>> msg = (ArrayList<HashMap<String,String>>) message;
		
		if(photoFlag==false)
		{
			if(msg.get(0).containsKey("MSG"))
			{
				System.out.println("send to observer: " + msg.get(0).get("MSG"));
				climsg  = new CliMessage(msg.get(0).get("MSG"));
			}
			else if(msg.get(0).containsKey("PHOTO"))
			{
				photoFlag = true;
				return;
			}
			else
			{
				System.out.println("send to observer: #Server: Search result");
				climsg  = new CliMessage("#Server: Search result",msg);
			}
			
		}
		else 
		{
			//set flag to false and deliver serialized photos and layers to observer
			photoFlag=false; 
			climsg = new CliMessage("#Server: Image", msg);
		}
		notifyObservers(climsg);
	  }
	  
	  
	  /**
	   * Hook method called after the connection has been closed.
	   */
	@Override
	  protected void connectionClosed() 
	  {
	    setChanged();
	    CliMessage msg = new CliMessage(CONNECTION_CLOSED);
	    notifyObservers(msg);
	  }
		
	  /**
	   * Hook method called each time an exception
	   * is raised by the client listening thread.
	   *
	   * @param exception the exception raised.
	   */
	
		@Override
	  protected void connectionException(Exception exception) 
	  {
	    setChanged();
	    exception.printStackTrace();
	    CliMessage msg = new CliMessage(CONNECTION_EXCEPTION);
	    notifyObservers(msg);
	  }

	  /**
	   * Hook method called after a connection has been established.
	   */
	  protected void connectionEstablished() 
	  {
	    setChanged();
	    CliMessage msg = new CliMessage(CONNECTION_ESTABLISHED);
	    notifyObservers(msg);
	  }
	
	
}
